﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Web;
using System.Text.RegularExpressions;

namespace EasyToHelp.Common
{
    public static class FileHelper
    {
        public static void WriteFile(Stream stream, string newFilePath, string newFileName)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(newFilePath);
            if (!dirInfo.Exists)
            {
                Directory.CreateDirectory(newFilePath);
            }
            string fullFileName = newFilePath + newFileName;
            FileStream fs = null;
            try
            {
                if (File.Exists(fullFileName))
                {
                    fs = File.OpenWrite(fullFileName);
                    //fs = new FileStream(fullFileName, FileMode.Append,
                    //FileAccess.Write, FileShare.Write);
                }
                else
                {
                    fs = new FileStream(fullFileName, FileMode.OpenOrCreate,
                    FileAccess.ReadWrite, FileShare.ReadWrite);
                }

                byte[] buf;
                try
                {
                    buf = StreamToBytes(stream);

                    //设定书写的開始位置为文件的末尾  
                    fs.Position = fs.Length;
                    //将待写入内容追加到文件末尾  
                    fs.Write(buf, 0, buf.Length);
                    fs.Flush();
                    fs.Close();
                    //len = fs.Length;
                    //fs.Lock(0, len);
                    //fs.Seek(0, SeekOrigin.End);
                    //fs.Write(buf, 0, buf.Length);
                    //fs.Unlock(0, len);
                    //fs.Flush();
                    //fs.Close();
                    //fs = null;
                }
                catch (Exception er)
                {
                    throw er;
                }
            }
            catch (Exception er)
            {
                throw er;
            }
        }
        /// <summary> 
        /// 将 Stream 转成 byte[] 
        /// </summary> 
        public static byte[] StreamToBytes(Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);

            // 设置当前流的位置为流的开始 
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }

        /// <summary> 
        /// 将 byte[] 转成 Stream 
        /// </summary> 
        public static Stream BytesToStream(byte[] bytes)
        {
            Stream stream = new MemoryStream(bytes);
            return stream;
        }
        /// <summary>
        /// 读取文件流
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public static string ReadFile(string FilePath, string FileName)
        {
            string fullFileName = FilePath + FileName;
            StringBuilder sb = new StringBuilder();
            using (System.IO.StreamReader sr = new System.IO.StreamReader(fullFileName))
            {
                string str;
                while ((str = sr.ReadLine()) != null)
                {
                    sb.Append(str);
                }
            }
            return sb.ToString();
        }


        public static void DeleteFile(string fullFilePath)
        {
            try
            {
                if (File.Exists(fullFilePath))
                {
                    File.Delete(fullFilePath);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        ///  将echarts返回的base64 转成图片
        /// </summary>
        /// <param name="image">图片的base64形式</param>
        /// <param name="proname">项目区分</param>
        public static string SaveImage(string image, string proname)
        {
            string filename = "/Uploads/" + string.Format("{0:yyyyMMdd}", DateTime.Now) + "/" + EncryptionMD5.CreateMd5(Guid.NewGuid().ToString()) + ".jpg";
            string path = $"{ Directory.GetCurrentDirectory() }/wwwroot" + filename;
            string filepath = Path.GetDirectoryName(path);
            // 如果不存在就创建file文件夹
            if (!Directory.Exists(filepath))
            {
                if (filepath != null) Directory.CreateDirectory(filepath);
            }
            //获取文件的ContentType
            // image = image.Split(',')[1];
            //var match = Regex.Match(image, "data:image/jpeg;base64,([\\w\\W]*)$");
            //if (match.Success)
            //{
            //    image = match.Groups[1].Value;
            //}
            var photoBytes = Convert.FromBase64String(image);
            System.IO.File.WriteAllBytes(path, photoBytes);
            return filename;
        }
        /// <summary>
        /// 返回文件后缀名
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string GetExtension(string filePath)
        {
           return Path.GetExtension(filePath);
        }
    }
}
